/*
 * MIT License
 *
 * Copyright (c) 2019 Mr.css
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package cn.seaboot.commons.reflect;

import cn.seaboot.commons.exception.ReflectException;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 枚举类型的工具
 *
 * @author Mr.css
 * @date 2021-02-08 11:42
 */
public class EnumUtils {
    private EnumUtils() {
    }

    /**
     * 枚举类名 转 枚举类对象
     *
     * @param clazz 全类名
     * @param name  枚举类名
     * @return 枚举类
     */
    public static Object valueOf(Class<?> clazz, String name) {
        try {
            Method method = clazz.getMethod("valueOf", String.class);
            return method.invoke(null, name);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new ReflectException("Can not case to enum: ", e);
        }
    }

    /**
     * 基于 COC 原则设计的函数，如果你的 enum 提供了码值转换函数，也可以用码值转换为 enum，
     * 这属于开发约定，不适用于所有场合。
     *
     * @param clazz 全类名
     * @param value 码值
     * @return 枚举类
     */
    public static Object valueOf(Class<?> clazz, Object value) {
        if (value instanceof String) {
            return valueOf(clazz, (String) value);
        } else {
            try {
                Method method = clazz.getMethod("valueOf", Integer.class);
                return method.invoke(null, (Integer) value);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                throw new ReflectException("Can not case to enum: ", e);
            }
        }
    }
}
